<template>
  <div class="login-page">
    <el-card>
      <template #header>面试宝典后台管理系统</template>

      <el-form ref="form" label-width="80px" :model="user" :rules="rules">
        <el-form-item class="unameInput" label="账号:" prop="username">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input show-password v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="login('form')" class="loginButton" type="primary"
            >登录</el-button
          >
          <el-button @click="reset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { loginApi } from '@/api/user'

export default {
  name: 'LoginIndex',
  data () {
    return {
      user: {
        username: 'admin',
        password: 'admin'
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login (formName) {
      // 验证表单
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            const res = await loginApi({
              username: this.user.username,
              password: this.user.password
            })
            // localStorage.setItem('pc-token', res.data.token)
            this.$store.commit('user/updateToken', res.data.token)
            this.$message.success('登录成功')
            this.$router.push('/dashboard')
          } catch (err) {
            if (err.response) {
              this.$message.error(err.response.data.message)
            } else {
              this.$message.error('登录失败')
            }
          }
        }
      })
    },
    reset (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center;
  background-size: cover;
}
.el-card {
  width: 420px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  ::v-deep .el-card__header {
    text-align: center;
    background-color: #727cf5;
    color: white;
    font-weight: 700;
    height: 70px;
    line-height: 35px;
  }
  .el-form {
    padding-right: 50px;
  }
  .unameInput {
    margin-top: 13px;
    margin-bottom: 25px;
  }
  .loginButton {
    margin-right: 40px;
    margin-left: 23px;
  }
}
</style>
